import javax.management.MBeanServerConnection;
import javax.management.MBeanServerInvocationHandler;
import javax.management.ObjectName;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;

import org.apache.activemq.broker.jmx.BrokerViewMBean;
import org.apache.activemq.broker.jmx.QueueViewMBean;

public class JMXServices {
	
	private static QueueViewMBean getNewQueueViewMBean(String queueName, BrokerViewMBean mbean,
			MBeanServerConnection mBeanServerConnection) throws Exception {
		mbean.addQueue(queueName);
		ObjectName name = mbean.getQueues()[mbean.getQueues().length - 1];
		QueueViewMBean queueMbean = (QueueViewMBean)MBeanServerInvocationHandler.
				newProxyInstance(mBeanServerConnection, name, QueueViewMBean.class, true);
		return queueMbean;
	}
	
	public static QueueViewMBean getQueueViewMBean(String queueName) throws Exception {
		
		JMXServiceURL jmxServiceURL = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://localhost:1099/jmxrmi");
		JMXConnector jmxConnector = JMXConnectorFactory.connect(jmxServiceURL);
		MBeanServerConnection mBeanServerConnection = jmxConnector.getMBeanServerConnection();
		//System.out.println(mBeanServerConnection.);
		
		ObjectName activeMQ = new ObjectName("org.apache.activemq:type=Broker,brokerName=localhost");
		BrokerViewMBean mbean =
				(BrokerViewMBean)MBeanServerInvocationHandler.newProxyInstance
				(mBeanServerConnection, activeMQ,BrokerViewMBean.class, true);
		
		for (ObjectName name : mbean.getQueues()) {

			QueueViewMBean queueMbean = (QueueViewMBean)MBeanServerInvocationHandler.
					newProxyInstance(mBeanServerConnection, name, QueueViewMBean.class, true);
			//System.out.println(name);
			if (queueMbean.getName().equals(queueName)) {
				return queueMbean;
			}
		}
		return getNewQueueViewMBean(queueName, mbean, mBeanServerConnection);		
	}
	
}
